package com.atzly.community.controller;

import com.atzly.community.constant.ActiveConstant;
import com.atzly.community.entity.User;
import com.atzly.community.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.Map;

/**  注册服务
 * @author zlysimida
 * @date 2021/8/26 - 11:01
 */
@Controller
public class RegisterController {

    @Autowired
    private UserService userService;

    @GetMapping("/user/register")
    public String register(){
        return "/site/register";
    }

    @PostMapping("/regist")
    public String register(Model model, User user){
        Map<String, Object> map = userService.registerService(user);
        if(map == null || map.isEmpty()){
            model.addAttribute("msg","注册成功,我们已经向您的邮箱发送了一封激活邮件,请尽快激活!");
            model.addAttribute("target", "/index");
            return "/site/operate-result";
        }else{
            model.addAttribute("usernameMsg",map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));
            model.addAttribute("emailMsg",map.get("emailMsg"));
            return "/site/register";
        }
    }

    // 邮箱验证的Urlhttp://localhost:8080/community/activation/101/code
    @GetMapping("/activation/{userId}/{code}")
    public String activation(Model model,
                             @PathVariable("userId") int userId,
                             @PathVariable("code") String code){
        int status = userService.activation(userId, code);
        if(status == ActiveConstant.ACTIVE_CONSTAN_SUCCESS.getCode()){
            model.addAttribute("msg", ActiveConstant.ACTIVE_CONSTAN_SUCCESS.getDescribe());
            model.addAttribute("target", "/login");
        }else if(status == ActiveConstant.ACTIVE_CONSTAN_REPEAT.getCode()){
            model.addAttribute("msg", ActiveConstant.ACTIVE_CONSTAN_REPEAT.getDescribe());
            model.addAttribute("target", "/index");
        }else{
            model.addAttribute("msg", ActiveConstant.ACTIVE_CONSTAN_DEFAULT.getDescribe());
            model.addAttribute("target", "/index");
        }
        return "/site/operate-result";
    }


}
